import { useState, useRef, useEffect } from 'react'; // 导入必要的React钩子
import { useNavigate } from 'react-router-dom'; // 导入路由导航钩子
import './VideoDetail.css'; // 复用视频详情页样式
import './ShortVideoPage.css'; // 导入短视频页面样式

// 短视频列表数据
const initialVideoList = [
  {
    id: '1',
    avatar: '/6.jpg', // 用户头像
    username: '滑板鞋', // 用户名
    likes: 176, // 点赞数
    comments: 1768, // 评论数
    shares: 25, // 分享数
    video: 'https://www.w3schools.com/html/movie.mp4', // 视频链接
    desc: '弹弓真好，声音震撼', // 视频描述
    music: '晴天', // 背景音乐
    userAvatar: '/6.jpg', // 用户头像
    isFollow: false, // 是否关注
    liked: false, // 是否点赞
    commentList: ["好棒！", "视频很赞"], // 评论列表
    tiktokId: '7959573175' // 抖音号
  },
  {
    id: '2',
    avatar: '/7.jpg',
    username: '滑板哥',
    likes: 200,
    comments: 888,
    shares: 30,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '滑板真帅',
    music: '夜空中最亮的星',
    userAvatar: '/7.jpg',
    isFollow: true,
    liked: false,
    commentList: ["666", "太酷了"],
    tiktokId: '7959573175'
  },
  {
    id: '3',
    avatar: '/9.jpg',
    username: '极限玩家',
    likes: 321,
    comments: 123,
    shares: 12,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '极限运动，挑战自我',
    music: '极限青春',
    userAvatar: '/9.jpg',
    isFollow: false,
    liked: false,
    commentList: ["太刺激了！"],
    tiktokId: '7959573175'
  },
  {
    id: '4',
    avatar: '/10.jpg',
    username: '美食家',
    likes: 512,
    comments: 256,
    shares: 40,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '美食分享，快乐生活',
    music: '美味人生',
    userAvatar: '/10.jpg',
    isFollow: true,
    liked: false,
    commentList: ["看饿了！", "求做法"],
    tiktokId: '7959573175'
  },
  {
    id: '5',
    avatar: '/11.jpg',
    username: '旅行者',
    likes: 789,
    comments: 333,
    shares: 55,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '世界那么大，我想去看看',
    music: '旅途',
    userAvatar: '/11.jpg',
    isFollow: false,
    liked: false,
    commentList: ["风景真美", "羡慕！"],
    tiktokId: '7959573175'
  },
  {
    id: '6',
    avatar: '/12.jpg',
    username: '短视频达人',
    likes: 120,
    comments: 45,
    shares: 10,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '15秒短视频，记录美好瞬间',
    music: '短暂的美好',
    userAvatar: '/12.jpg',
    isFollow: false,
    liked: false,
    commentList: ["短视频也精彩！"],
    tiktokId: '7959573175'
  },
  {
    id: '7',
    avatar: '/13.jpg',
    username: '风景控',
    likes: 999,
    comments: 500,
    shares: 80,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '祖国大好河山，美不胜收',
    music: '山水之间',
    userAvatar: '/13.jpg',
    isFollow: true,
    liked: false,
    commentList: ["太美了", "想去旅行"],
    tiktokId: '7959573175'
  },
  {
    id: '8',
    avatar: '/14.jpg',
    username: '搞笑小王',
    likes: 666,
    comments: 222,
    shares: 66,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '笑一笑，十年少！',
    music: '快乐每一天',
    userAvatar: '/14.jpg',
    isFollow: false,
    liked: false,
    commentList: ["哈哈哈", "太逗了"],
    tiktokId: '7959573175'
  },
  {
    id: '9',
    avatar: '/6.jpg',
    username: '潮流达人',
    likes: 1287,
    comments: 435,
    shares: 128,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '今日穿搭分享，简约时尚风',
    music: '时尚节拍',
    userAvatar: '/6.jpg',
    isFollow: false,
    liked: false,
    commentList: ["好看！", "在哪买的？", "求同款链接"],
    tiktokId: '7959573175'
  },
  {
    id: '10',
    avatar: '/7.jpg',
    username: '厨艺小当家',
    likes: 1543,
    comments: 521,
    shares: 216,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '十分钟快手菜，解决你的晚餐',
    music: '烹饪时光',
    userAvatar: '/7.jpg',
    isFollow: true,
    liked: false,
    commentList: ["学到了！", "今晚就做这个", "看起来好美味"],
    tiktokId: '7959573175'
  },
  {
    id: '11',
    avatar: '/9.jpg',
    username: '瑜伽教练',
    likes: 894,
    comments: 342,
    shares: 87,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '每日一式，强健体魄',
    music: '身心平衡',
    userAvatar: '/9.jpg',
    isFollow: false,
    liked: false,
    commentList: ["太专业了", "练了一周，感觉腰不疼了"],
    tiktokId: '7959573175'
  },
  {
    id: '12',
    avatar: '/10.jpg',
    username: '数码评测师',
    likes: 1023,
    comments: 489,
    shares: 154,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '新款手机深度评测，值不值得买？',
    music: '科技未来',
    userAvatar: '/10.jpg',
    isFollow: true,
    liked: false,
    commentList: ["讲解很专业", "买它！", "价格怎么样？"],
    tiktokId: '7959573175'
  },
  {
    id: '13',
    avatar: '/11.jpg',
    username: '插画师日常',
    likes: 763,
    comments: 231,
    shares: 92,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '手绘过程分享，治愈日常',
    music: '艺术空间',
    userAvatar: '/11.jpg',
    isFollow: false,
    liked: false,
    commentList: [
      {
        id: 'c1',
        userId: 'user1',
        username: '艺术爱好者',
        avatar: '/6.jpg',
        content: '太有才了',
        likes: 56,
        timestamp: '2小时前',
        replies: [
          {
            id: 'r1',
            userId: 'user2',
            username: '插画师日常',
            avatar: '/11.jpg',
            content: '谢谢支持',
            likes: 12,
            timestamp: '1小时前',
            replies: []
          },
          {
            id: 'r2',
            userId: 'user3',
            username: '设计学习者',
            avatar: '/12.jpg',
            content: '能分享一下使用的软件吗？',
            likes: 8,
            timestamp: '45分钟前',
            replies: []
          }
        ]
      },
      {
        id: 'c2',
        userId: 'user4',
        username: '数字绘画爱好者',
        avatar: '/7.jpg',
        content: '画得真好',
        likes: 34,
        timestamp: '1小时前',
        replies: []
      },
      {
        id: 'c3',
        userId: 'user5',
        username: '新手画家',
        avatar: '/13.jpg',
        content: '用的什么软件？',
        likes: 22,
        timestamp: '50分钟前',
        replies: [
          {
            id: 'r3',
            userId: 'user1',
            username: '插画师日常',
            avatar: '/11.jpg',
            content: '我用的是Procreate',
            likes: 15,
            timestamp: '30分钟前',
            replies: []
          }
        ]
      }
    ],
    tiktokId: '7959573175'
  },
  {
    id: '14',
    avatar: '/12.jpg',
    username: '街头魔术师',
    likes: 1756,
    comments: 632,
    shares: 287,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '街头魔术表演，揭秘背后技巧',
    music: '神秘魔法',
    userAvatar: '/12.jpg',
    isFollow: true,
    liked: false,
    commentList: ["太神奇了", "看不懂原理", "再看十遍"],
    tiktokId: '7959573175'
  },
  {
    id: '15',
    avatar: '/13.jpg',
    username: '育儿博主',
    likes: 932,
    comments: 485,
    shares: 176,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '宝宝辅食制作，营养又美味',
    music: '童年时光',
    userAvatar: '/13.jpg',
    isFollow: false,
    liked: false,
    commentList: ["谢谢分享", "孩子很喜欢", "收藏了"],
    tiktokId: '7959573175'
  },
  {
    id: '16',
    avatar: '/14.jpg',
    username: '汽车玩家',
    likes: 2134,
    comments: 765,
    shares: 324,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '超跑声浪合集，引擎咆哮',
    music: '速度与激情',
    userAvatar: '/14.jpg',
    isFollow: true,
    liked: false,
    commentList: ["声音太震撼了", "梦想座驾", "买不起看看也好"],
    tiktokId: '7959573175'
  }
];

export default function ShortVideoPage() {
  const navigate = useNavigate(); // 导航钩子
  const [videoList, setVideoList] = useState(initialVideoList); // 视频列表状态
  const [current, setCurrent] = useState(0); // 当前视频索引
  const [loading, setLoading] = useState(false); // 加载状态
  const [hasMore, setHasMore] = useState(true); // 是否有更多视频
  const [showComment, setShowComment] = useState(false); // 是否显示评论
  const [commentInput, setCommentInput] = useState(""); // 评论输入
  const [isTransitioning, setIsTransitioning] = useState(false); // 是否正在过渡
  const [direction, setDirection] = useState(null); // 滑动方向
  const [showGuide, setShowGuide] = useState(true); // 是否显示手势引导
  const [swipeHint, setSwipeHint] = useState(null); // 滑动提示
  const [progress, setProgress] = useState(0); // 视频进度
  const [isPlaying, setIsPlaying] = useState(false); // 视频是否正在播放
  const [showPlayButton, setShowPlayButton] = useState(true); // 是否显示播放按钮
  const [showConfirmUnfollow, setShowConfirmUnfollow] = useState(false); // 是否显示取消关注确认
  const [userToUnfollow, setUserToUnfollow] = useState(null); // 要取消关注的用户
  
  // 添加评论相关状态
  const [replyTo, setReplyTo] = useState(null); // 当前回复对象 (null 表示顶级评论)
  const [replyToComment, setReplyToComment] = useState(null); // 回复给哪条评论
  const [replyToUser, setReplyToUser] = useState(null); // 回复给哪个用户
  const [replyLevel, setReplyLevel] = useState(0); // 回复级别 (0: 顶级, 1: 二级, 2: 三级)
  
  // 引用
  const startY = useRef(null); // 触摸起始位置
  const videoRefs = useRef({}); // 视频元素引用
  const containerRef = useRef(null); // 容器引用
  const progressInterval = useRef(null); // 进度条定时器
  
  // 处理视频播放和进度
  useEffect(() => {
    // 获取当前视频元素
    const currentVideo = videoRefs.current[current];
    if (currentVideo) {
      // 重置播放状态
      setIsPlaying(false);
      setShowPlayButton(true);
      
      // 预加载视频
      currentVideo.load();
      
      // 暂停其他视频
      Object.keys(videoRefs.current).forEach(key => {
        const index = parseInt(key);
        if (index !== current && videoRefs.current[index]) {
          videoRefs.current[index].pause();
          videoRefs.current[index].currentTime = 0; // 重置视频时间
        }
      });
      
      // 设置进度条更新
      if (progressInterval.current) {
        clearInterval(progressInterval.current);
      }
      
      progressInterval.current = setInterval(() => {
        if (currentVideo) {
          const progress = (currentVideo.currentTime / currentVideo.duration) * 100;
          setProgress(progress);
        }
      }, 100);
    }
    
    // 清理函数
    return () => {
      if (progressInterval.current) {
        clearInterval(progressInterval.current);
      }
    };
  }, [current]);
  
  // 检查是否是第一次访问
  useEffect(() => {
    const hasVisited = localStorage.getItem('hasVisitedShortVideo');
    if (hasVisited) {
      setShowGuide(false);
    }
  }, []);
  
  // 关闭引导并记住
  const closeGuide = () => {
    setShowGuide(false);
    localStorage.setItem('hasVisitedShortVideo', 'true');
  };
  
  // 鼠标按下事件处理
  const handleMouseDown = (e) => {
    if (showGuide) return; // 如果显示引导，不处理滑动
    
    startY.current = e.clientY; // 记录起始Y坐标
    window.addEventListener("mousemove", handleMouseMove); // 添加移动事件监听
    window.addEventListener("mouseup", handleMouseUp); // 添加松开事件监听
  };
  
  // 鼠标移动事件处理
  const handleMouseMove = (e) => {
    if (startY.current === null || isTransitioning) return;
    
    const deltaY = e.clientY - startY.current; // 计算Y轴移动距离
    const container = containerRef.current;
    
    if (container) {
      // 根据移动距离应用变换效果
      container.style.transform = `translateY(${deltaY}px)`;
      container.style.transition = 'none';
      
      // 设置移动方向
      if (deltaY > 0) {
        setDirection('down');
      } else if (deltaY < 0) {
        setDirection('up');
      }
    }
  };
  
  // 鼠标松开事件处理
  const handleMouseUp = (e) => {
    window.removeEventListener("mousemove", handleMouseMove); // 移除移动事件监听
    window.removeEventListener("mouseup", handleMouseUp); // 移除松开事件监听
    
    if (startY.current === null || isTransitioning) return;
    
    const deltaY = e.clientY - startY.current; // 计算Y轴移动距离
    const container = containerRef.current;
    
    // 重置容器样式
    if (container) {
      container.style.transform = '';
      container.style.transition = 'transform 0.3s ease';
    }
    
    // 根据移动距离切换视频
    if (deltaY > 80 && current > 0) {
      // 向下滑动，显示上一个视频
      handlePrev();
      // 显示滑动提示
      showSwipeHint('down');
    } else if (deltaY < -80 && current < videoList.length - 1) {
      // 向上滑动，显示下一个视频
      handleNext();
      // 显示滑动提示
      showSwipeHint('up');
    }
    
    startY.current = null; // 重置起始位置
    setDirection(null); // 重置方向
  };
  
  // 触摸开始事件处理
  const handleTouchStart = (e) => {
    if (showGuide) return; // 如果显示引导，不处理滑动
    
    startY.current = e.touches[0].clientY; // 记录触摸起始Y坐标
  };
  
  // 触摸移动事件处理
  const handleTouchMove = (e) => {
    if (startY.current === null || isTransitioning) return;
    
    const deltaY = e.touches[0].clientY - startY.current; // 计算Y轴移动距离
    const container = containerRef.current;
    
    if (container) {
      // 根据移动距离应用变换效果
      container.style.transform = `translateY(${deltaY}px)`;
      container.style.transition = 'none';
      
      // 设置移动方向
      if (deltaY > 0) {
        setDirection('down');
      } else if (deltaY < 0) {
        setDirection('up');
      }
    }
  };
  
  // 触摸结束事件处理
  const handleTouchEnd = (e) => {
    if (startY.current === null || isTransitioning) return;
    
    const deltaY = e.changedTouches[0].clientY - startY.current; // 计算Y轴移动距离
    const container = containerRef.current;
    
    // 重置容器样式
    if (container) {
      container.style.transform = '';
      container.style.transition = 'transform 0.3s ease';
    }
    
    // 根据移动距离切换视频
    if (deltaY > 80 && current > 0) {
      // 向下滑动，显示上一个视频
      handlePrev();
      // 显示滑动提示
      showSwipeHint('down');
    } else if (deltaY < -80 && current < videoList.length - 1) {
      // 向上滑动，显示下一个视频
      handleNext();
      // 显示滑动提示
      showSwipeHint('up');
    }
    
    startY.current = null; // 重置起始位置
    setDirection(null); // 重置方向
  };
  
  // 显示滑动提示
  const showSwipeHint = (direction) => {
    setSwipeHint(direction);
    setTimeout(() => {
      setSwipeHint(null);
    }, 1000);
  };
  
  // 处理上一个视频
  const handlePrev = () => {
    if (current > 0 && !isTransitioning) {
      setIsTransitioning(true); // 设置过渡状态
      setCurrent(current - 1); // 更新当前索引
      setProgress(0); // 重置进度
      
      // 过渡动画结束后重置状态
      setTimeout(() => {
        setIsTransitioning(false);
      }, 300);
    }
  };
  
  // 处理下一个视频
  const handleNext = () => {
    if (current < videoList.length - 1 && !isTransitioning) {
      setIsTransitioning(true); // 设置过渡状态
      setCurrent(current + 1); // 更新当前索引
      setProgress(0); // 重置进度
      
      // 过渡动画结束后重置状态
      setTimeout(() => {
        setIsTransitioning(false);
      }, 300);
    } else if (current === videoList.length - 1 && hasMore && !loading) {
      // 如果是最后一个视频且有更多数据，加载更多
      setLoading(true);
      
      // 模拟异步加载更多视频
      setTimeout(() => {
        // 这里可以替换为实际的API请求
        setHasMore(false); // 假设没有更多数据了
        setLoading(false);
      }, 1500);
    }
  };
  
  // 点赞操作
  const handleLike = () => {
    setVideoList(list => list.map((v, idx) =>
      idx === current
        ? {
            ...v,
            liked: !v.liked,
            likes: v.liked ? v.likes - 1 : v.likes + 1
          }
        : v
    ));
  };
  
  // 处理评论操作
  const handleComment = () => {
    setReplyTo(null); // 重置回复状态
    setReplyToComment(null);
    setReplyToUser(null);
    setReplyLevel(0);
    setCommentInput(""); // 清空输入
    setShowComment(true); // 显示评论面板
  };
  
  // 点击回复按钮
  const handleReply = (comment, user, level, parentComment = null) => {
    setReplyTo(comment);
    setReplyToUser(user);
    setReplyLevel(level);
    setReplyToComment(parentComment || comment);
    setCommentInput("");
    setShowComment(true);
    
    // 设置输入框占位符
    setTimeout(() => {
      const input = document.querySelector('.comment-input');
      if (input) {
        input.focus();
      }
    }, 100);
  };

  // 取消回复
  const cancelReply = () => {
    setReplyTo(null);
    setReplyToUser(null);
    setReplyLevel(0);
    setReplyToComment(null);
  };
  
  // 评论提交
  const handleCommentSubmit = (e) => {
    e.preventDefault();
    if (!commentInput.trim()) return;
    
    const newComment = {
      id: `c${Date.now()}`,
      userId: `user${Math.floor(Math.random() * 1000)}`,
      username: "当前用户",
      avatar: "/14.jpg",
      content: commentInput.trim(),
      likes: 0,
      timestamp: "刚刚",
      replies: []
    };
    
    // 根据回复级别添加评论
    if (!replyTo) {
      // 添加顶级评论
      setVideoList(list => list.map((v, idx) =>
        idx === current
          ? {
              ...v,
              comments: v.comments + 1,
              commentList: [newComment, ...v.commentList]
            }
          : v
      ));
    } else if (replyLevel === 1) {
      // 添加二级回复
      setVideoList(list => list.map((v, idx) =>
        idx === current
          ? {
              ...v,
              comments: v.comments + 1,
              commentList: v.commentList.map(comment => 
                comment.id === replyTo.id
                  ? { ...comment, replies: [newComment, ...comment.replies] }
                  : comment
              )
            }
          : v
      ));
    } else if (replyLevel === 2) {
      // 添加三级回复
      setVideoList(list => list.map((v, idx) =>
        idx === current
          ? {
              ...v,
              comments: v.comments + 1,
              commentList: v.commentList.map(comment => 
                comment.id === replyToComment.id
                  ? { 
                      ...comment, 
                      replies: comment.replies.map(reply => 
                        reply.id === replyTo.id
                          ? { ...reply, replies: [newComment, ...reply.replies] }
                          : reply
                      )
                    }
                  : comment
              )
            }
          : v
      ));
    }
    
    setCommentInput(""); // 清空输入
    cancelReply(); // 清除回复状态
  };

  // 处理点赞评论
  const handleLikeComment = (commentId, replyId = null, subReplyId = null) => {
    setVideoList(list => list.map((v, idx) =>
      idx === current
        ? {
            ...v,
            commentList: v.commentList.map(comment => {
              // 如果是顶级评论
              if (!replyId && comment.id === commentId) {
                return { ...comment, likes: comment.likes + 1 };
              }
              
              // 如果是二级评论
              if (replyId && !subReplyId && comment.id === commentId) {
                return {
                  ...comment,
                  replies: comment.replies.map(reply =>
                    reply.id === replyId
                      ? { ...reply, likes: reply.likes + 1 }
                      : reply
                  )
                };
              }
              
              // 如果是三级评论
              if (replyId && subReplyId && comment.id === commentId) {
                return {
                  ...comment,
                  replies: comment.replies.map(reply =>
                    reply.id === replyId
                      ? { 
                          ...reply, 
                          replies: reply.replies.map(subReply =>
                            subReply.id === subReplyId
                              ? { ...subReply, likes: subReply.likes + 1 }
                              : subReply
                          )
                        }
                      : reply
                  )
                };
              }
              
              return comment;
            })
          }
        : v
    ));
  };
  
  // 处理关注/取消关注
  const handleFollow = (e, index) => {
    e.stopPropagation(); // 防止事件冒泡触发视频播放

    const videoIndex = index !== undefined ? index : current;
    const currentVideo = videoList[videoIndex];

    if (currentVideo.isFollow) {
      // 如果已关注，显示确认取消关注的弹窗
      setUserToUnfollow(videoIndex);
      setShowConfirmUnfollow(true);
    } else {
      // 如果未关注，直接关注
      setVideoList(list => list.map((v, idx) =>
        idx === videoIndex
          ? { ...v, isFollow: true }
          : v
      ));
    }
  };

  // 确认取消关注
  const confirmUnfollow = () => {
    if (userToUnfollow !== null) {
      setVideoList(list => list.map((v, idx) =>
        idx === userToUnfollow
          ? { ...v, isFollow: false }
          : v
      ));
      setShowConfirmUnfollow(false);
      setUserToUnfollow(null);
    }
  };

  // 取消弹窗
  const cancelUnfollow = () => {
    setShowConfirmUnfollow(false);
    setUserToUnfollow(null);
  };
  
  // 获取当前视频数据
  const video = videoList[current];
  
  // 处理播放/暂停视频
  const handlePlayPause = () => {
    const currentVideo = videoRefs.current[current];
    
    if (currentVideo) {
      if (currentVideo.paused) {
        // 播放视频
        const playPromise = currentVideo.play();
        
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              setIsPlaying(true);
              setShowPlayButton(false);
              setTimeout(() => {
                // 2秒后自动隐藏播放按钮
                setShowPlayButton(false);
              }, 2000);
            })
            .catch(error => {
              console.error("视频播放失败:", error);
              setIsPlaying(false);
              setShowPlayButton(true);
            });
        }
      } else {
        // 暂停视频
        currentVideo.pause();
        setIsPlaying(false);
        setShowPlayButton(true);
      }
    }
  };
  
  // 当视频点击时
  const handleVideoClick = (e) => {
    // 阻止事件冒泡
    e.stopPropagation();
    handlePlayPause();
  };
  
  // 视频加载完成事件
  const handleVideoLoaded = () => {
    const currentVideo = videoRefs.current[current];
    
    // 在移动设备上，尝试自动播放视频
    if (currentVideo && 'ontouchstart' in window) {
      setTimeout(() => {
        handlePlayPause();
      }, 300);
    }
  };
  
  // 渲染视频指示器
  const renderIndicators = () => {
    return (
      <div className="video-indicators">
        {videoList.map((_, index) => (
          <div 
            key={index} 
            className={`indicator ${index === current ? 'active' : ''}`}
            onClick={() => {
              if (!isTransitioning) {
                setCurrent(index);
                setProgress(0); // 重置进度
              }
            }}
          />
        ))}
      </div>
    );
  };
  
  return (
    <div className="short-video-page">
      {/* 返回按钮 */}
      <div className="back-btn" onClick={() => navigate('/discover')}>
        <span>&lt;</span>
      </div>
      
      {/* 视频容器 */}
      <div 
        className="video-container"
        ref={containerRef}
        onMouseDown={handleMouseDown}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {/* 视频列表 */}
        {videoList.map((item, index) => (
          <div 
            key={item.id} 
            className={`video-item ${index === current ? 'active' : ''} ${index < current ? 'prev' : ''} ${index > current ? 'next' : ''}`}
          >
            <video
              ref={el => videoRefs.current[index] = el}
              src={item.video}
              loop
              playsInline
              poster={item.avatar}
              onClick={handleVideoClick}
              onLoadedData={index === current ? handleVideoLoaded : undefined}
              muted // 初始静音，用户可以手动打开声音
            />
            
            {/* 播放按钮 */}
            {index === current && showPlayButton && (
              <div className="play-button-container" onClick={handlePlayPause}>
                <div className="play-button-large">
                  {isPlaying ? (
                    <svg viewBox="0 0 24 24" width="64" height="64">
                      <path fill="#fff" d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path>
                    </svg>
                  ) : (
                    <svg viewBox="0 0 24 24" width="64" height="64">
                      <path fill="#fff" d="M8 5v14l11-7z"></path>
                    </svg>
                  )}
                </div>
              </div>
            )}
            
            {/* 抖音号水印 */}
            <div className="tiktok-id">抖音号：{item.tiktokId || '7959573175'}</div>
            
            {/* 视频信息 */}
            <div className="video-info">
              <div className="user-info">
                <img src={item.avatar} alt="用户头像" className="user-avatar" />
                <span className="username">{item.username}</span>
                <button 
                  className={`follow-btn ${item.isFollow ? 'following' : ''}`}
                  onClick={(e) => handleFollow(e, index)}
                >
                  {item.isFollow ? '已关注' : '关注'}
                </button>
              </div>
              <div className="video-desc">{item.desc}</div>
              <div className="video-music">
                <span className="music-icon">♫</span>
                <span className="music-name">{item.music}</span>
              </div>
            </div>
            
            {/* 视频操作 */}
            <div className="video-actions">
              <div 
                className={`action-item ${item.liked ? 'liked' : ''}`} 
                onClick={handleLike}
              >
                <div className="action-icon like-icon">
                  <svg viewBox="0 0 24 24" width="32" height="32">
                    <path fill={item.liked ? "#ff2c55" : "#fff"} d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"></path>
                  </svg>
                </div>
                <span className="action-count">{item.likes}</span>
              </div>
              <div className="action-item" onClick={handleComment}>
                <div className="action-icon comment-icon">
                  <svg viewBox="0 0 24 24" width="32" height="32">
                    <path fill="#fff" d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"></path>
                  </svg>
                </div>
                <span className="action-count">{item.comments}</span>
              </div>
              <div className="action-item">
                <div className="action-icon share-icon">
                  <svg viewBox="0 0 24 24" width="32" height="32">
                    <path fill="#fff" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"></path>
                  </svg>
                </div>
                <span className="action-count">{item.shares}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
      
      {/* 进度条 */}
      <div className="progress-container">
        <div className="progress-bar" style={{width: `${progress}%`}}></div>
      </div>
      
      {/* 滑动提示 */}
      {swipeHint && (
        <div className={`swipe-hint ${swipeHint}`}>
          {swipeHint === 'up' ? '上滑查看下一个视频' : '下滑查看上一个视频'}
        </div>
      )}
      
      {/* 加载指示器 */}
      {loading && (
        <div className="loading-indicator">
          <div className="spinner"></div>
          <div className="loading-text">正在加载更多视频...</div>
        </div>
      )}
      
      {/* 手势引导 */}
      {showGuide && (
        <div className="guide-overlay" onClick={closeGuide}>
          <div className="guide-content">
            <h3>滑动浏览短视频</h3>
            <p>上滑查看下一个视频，下滑查看上一个视频</p>
            <p>点击视频可以暂停/播放</p>
            <button className="guide-btn" onClick={closeGuide}>知道了</button>
          </div>
        </div>
      )}
      
      {/* 评论面板 */}
      {showComment && (
        <div className="comment-panel">
          <div className="comment-header">
            <div className="comment-title">评论 ({video.comments})</div>
            <div className="close-btn" onClick={() => setShowComment(false)}>×</div>
          </div>
          <div className="comment-list">
            {video.commentList.length > 0 ? (
              video.commentList.map((comment) => (
                <div key={comment.id} className="comment-item">
                  <img src={comment.avatar} alt={comment.username} className="comment-avatar" />
                  <div className="comment-content">
                    <div className="comment-user">{comment.username}</div>
                    <div className="comment-text">{comment.content}</div>
                    <div className="comment-actions">
                      <span className="comment-time">{comment.timestamp}</span>
                      <div className="comment-buttons">
                        <button className="like-btn" onClick={() => handleLikeComment(comment.id)}>
                          <i className="like-icon">❤️</i> {comment.likes}
                        </button>
                        <button className="reply-btn" onClick={() => handleReply(comment, comment.username, 1)}>
                          回复
                        </button>
                      </div>
                    </div>
                    
                    {/* 二级评论 */}
                    {comment.replies && comment.replies.length > 0 && (
                      <div className="reply-list">
                        {comment.replies.map((reply) => (
                          <div key={reply.id} className="reply-item">
                            <img src={reply.avatar} alt={reply.username} className="reply-avatar" />
                            <div className="reply-content">
                              <div className="reply-user">{reply.username}</div>
                              <div className="reply-text">{reply.content}</div>
                              <div className="reply-actions">
                                <span className="reply-time">{reply.timestamp}</span>
                                <div className="reply-buttons">
                                  <button className="like-btn" onClick={() => handleLikeComment(comment.id, reply.id)}>
                                    <i className="like-icon">❤️</i> {reply.likes}
                                  </button>
                                  <button className="reply-btn" onClick={() => handleReply(reply, reply.username, 2, comment)}>
                                    回复
                                  </button>
                                </div>
                              </div>
                              
                              {/* 三级评论 */}
                              {reply.replies && reply.replies.length > 0 && (
                                <div className="subreply-list">
                                  {reply.replies.map((subReply) => (
                                    <div key={subReply.id} className="subreply-item">
                                      <img src={subReply.avatar} alt={subReply.username} className="subreply-avatar" />
                                      <div className="subreply-content">
                                        <div className="subreply-user">{subReply.username}</div>
                                        <div className="subreply-text">{subReply.content}</div>
                                        <div className="subreply-actions">
                                          <span className="subreply-time">{subReply.timestamp}</span>
                                          <button className="like-btn" onClick={() => handleLikeComment(comment.id, reply.id, subReply.id)}>
                                            <i className="like-icon">❤️</i> {subReply.likes}
                                          </button>
                                        </div>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              ))
            ) : (
              <div className="comment-empty">还没有评论，快来抢沙发~</div>
            )}
          </div>
          <form className="comment-form" onSubmit={handleCommentSubmit}>
            {replyTo && (
              <div className="reply-info">
                回复 <span className="reply-username">@{replyToUser}</span>
                <button type="button" className="cancel-reply" onClick={cancelReply}>×</button>
              </div>
            )}
            <input
              type="text"
              className="comment-input"
              placeholder={replyTo ? `回复 @${replyToUser}...` : "添加评论..."}
              value={commentInput}
              onChange={e => setCommentInput(e.target.value)}
            />
            <button 
              type="submit" 
              className="comment-submit"
              disabled={!commentInput.trim()}
            >
              发送
            </button>
          </form>
        </div>
      )}
      
      {/* 取消关注确认弹窗 */}
      {showConfirmUnfollow && (
        <div className="confirm-dialog-overlay">
          <div className="confirm-dialog">
            <div className="confirm-dialog-title">
              确定要取消关注{userToUnfollow !== null ? videoList[userToUnfollow].username : '作者'}吗？
            </div>
            <div className="confirm-dialog-buttons">
              <button className="confirm-dialog-cancel" onClick={cancelUnfollow}>
                取消
              </button>
              <button className="confirm-dialog-confirm" onClick={confirmUnfollow}>
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
} 